package main.com.oaer.action;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import main.com.oaer.model.RolePurview;
import main.com.oaer.service.RolePurviewService;
import main.com.oaer.util.CommonUtil;
import main.com.oaer.util.JsonPluginsUtil;

/**
 * 角色、权限控制器
 *
 */
@Controller
@RequestMapping("/rolePurview")
public class RolePurviewAction {
    
	@Autowired
	RolePurviewService rolePurviewService;
	
	/**
	 * 为角色分配权限,以json格式异步返回消息
	 * @param roleId 角色id
	 * @param purviewIds  权限id字符串 ，如：10,11,12,13,15
	 */
	@RequestMapping(value="/add")
	public void add(HttpServletResponse response, Long roleId, String purviewIds){
		String[] purviewId  = purviewIds.split(",");
		  Long[] lpurviewId = CommonUtil.stringToLong(purviewId);
		  List<RolePurview> rolePurviewList = new LinkedList<RolePurview>();
		  for(Long id:lpurviewId){
			  RolePurview rolePurview = new RolePurview();
			  rolePurview.setPurviewId(id);
			  rolePurview.setRoleId(roleId);
			  rolePurviewList.add(rolePurview);
		  }
		  rolePurviewService.add(rolePurviewList,roleId);
		  Map<String,Object> map = new HashMap<String,Object>();
		  map.put("status", "success");
		  CommonUtil.printToHTML(response, map);
	}
	
	/**
	 * 查找某角色的权限列表，并转到分配权限页面
	 * @param modleMap 模型对象
	 * @param roleId 角色id
	 * @return "system/assignPurview"  分配权限页面
	 */
	@RequestMapping(value="/assignPurview")
	public String assignPurview(ModelMap modelMap,Long roleId){
		List<Map<String, Object>> purviewsList = rolePurviewService.findAllPurviewByRole(roleId);
		modelMap.put("purviewsList", JsonPluginsUtil.listToJson(purviewsList));
		modelMap.put("roleId", roleId);
		return "system/assignPurview";
	}
}
